package com.xzh.homeliving.commodity.service.impl;

import com.xzh.homeliving.commodity.dao.BrandDao;
import com.xzh.homeliving.commodity.dao.CategoryDao;
import com.xzh.homeliving.commodity.entity.BrandEntity;
import com.xzh.homeliving.commodity.entity.CategoryEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzh.common.utils.PageUtils;
import com.xzh.common.utils.Query;

import com.xzh.homeliving.commodity.dao.CategoryBrandRelationDao;
import com.xzh.homeliving.commodity.entity.CategoryBrandRelationEntity;
import com.xzh.homeliving.commodity.service.CategoryBrandRelationService;

import javax.annotation.Resource;


/**
 * @author xzh
 */
@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {
    @Resource
    private BrandDao brandDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAll(CategoryBrandRelationEntity categoryBrandRelationEntity) {
        CategoryEntity categoryEntity = categoryDao.selectById(categoryBrandRelationEntity.getCategoryId());
        BrandEntity brandEntity = brandDao.selectById(categoryBrandRelationEntity.getBrandId());
        categoryBrandRelationEntity.setCategoryName(categoryEntity.getName());
        categoryBrandRelationEntity.setBrandName(brandEntity.getName());
        this.save(categoryBrandRelationEntity);
    }

    @Override
    public List<BrandEntity> getBrandByCategoryId(Long categoryId) {
        // 1. 先在关联表中查找categoryId符合的关联组的品牌id
        List<CategoryBrandRelationEntity> categoryBrandRelationEntities = categoryBrandRelationDao.selectList(new QueryWrapper<CategoryBrandRelationEntity>().eq("category_id", categoryId));
        List<Long> brandIds = categoryBrandRelationEntities.stream().map(CategoryBrandRelationEntity::getBrandId).collect(Collectors.toList());
        if(brandIds.isEmpty()) {
            return new ArrayList<>();
        } else {
            return brandDao.selectList(new QueryWrapper<BrandEntity>().in("id", brandIds));
        }
    }

}